package v4.text;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.Reader;
import java.io.Writer;
import java.nio.charset.Charset;

public class FileTxtKit {
	
	public static String getTxtKey(File key) {
		return getTxtKey(key, Charset.forName("UTF-8"));
	}
	public static String getTxtKey(File key, Charset charset) {
		if(key!=null) {
			Reader fr = null;
			BufferedReader br = null;
			try {
				fr = new InputStreamReader(new FileInputStream(key), charset);
				br = new BufferedReader(fr);
				String line = null;
				StringBuilder sb = new StringBuilder();
				while((line=br.readLine())!=null) {
					sb.append(line);
				}
				return sb.toString();
			} catch (FileNotFoundException e) {
				e.printStackTrace();
				throw new RuntimeException(e.getMessage());
			} catch (IOException e) {
				e.printStackTrace();
				throw new RuntimeException(e.getMessage());
			} finally {
				try {
					if(br!=null) br.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
				try {
					if(fr!=null) fr.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			
		}
		return null;
	}
	
	public static boolean saveText(File key, String text, boolean override) {
		if(!override && key.exists()) {
			return false;
		}
		Writer writer = null;
		BufferedWriter bw = null;
		try {
			writer = new OutputStreamWriter(new FileOutputStream(key));
			bw = new BufferedWriter(writer);
			bw.write(text);
			bw.flush();
			return true;
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			throw new RuntimeException(e.getMessage());
		} catch (IOException e) {
			e.printStackTrace();
			throw new RuntimeException(e.getMessage());
		} finally {
			try {
				if(bw!=null) bw.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
			try {
				if(writer!=null) writer.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		
	}

}
